package com.tiger.web.controller.oaInfo;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.tiger.common.annotation.Log;
import com.tiger.common.core.controller.BaseController;
import com.tiger.common.core.domain.AjaxMapResult;
import com.tiger.common.core.domain.AjaxResult;
import com.tiger.common.core.domain.model.LoginUser;
import com.tiger.common.core.page.TableDataInfo;
import com.tiger.common.enums.BusinessType;
import com.tiger.common.utils.ServletUtils;
import com.tiger.common.utils.spring.SpringUtils;
import com.tiger.communal.domain.ConstructionUnit;
import com.tiger.framework.web.service.TokenService;
import com.tiger.project.domain.*;
import com.tiger.project.domain.req.FlowInfo;
import com.tiger.project.mapper.AssetMapper;
import com.tiger.project.service.IOainfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.ApiParam;
import okhttp3.*;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * OA消息待办已办Controller
 *
 * @author iot
 * @date 2022-12-13
 */
@Api(tags = "OA信息")
@RestController
@RequestMapping("/tiger/oainfo")
@CrossOrigin
public class OainfoController extends BaseController {
    @Autowired
    private IOainfoService oainfoService;

    /**
     * 查询OA消息集成列表
     */
    @ApiOperation(value = "查询OA消息集成")
    //@PreAuthorize("@ss.hasPermi('tiger:oainfo:list')")
    @GetMapping("/list")
        public TableDataInfo list(Oainfo oainfo) {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        oainfo.setRecipientId(loginUser.getUser().getOaId());
        startPage();
        List<Oainfo> list = oainfoService.selectOainfoList(oainfo);
        return getDataTable(list);
    }

    /**
     * 获取OA消息集成详细信息
     */
//    @ApiOperation(value = "获取OA消息待办已办列详细信息")
//    //@PreAuthorize("@ss.hasPermi('tiger:oainfo:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id) {
//        return AjaxResult.success(oainfoService.selectOainfoById(id));
//    }


    /**
     * 新增OA消息集成
     */
    @ApiOperation(value = "新增OA消息集成")
    //@PreAuthorize("@ss.hasPermi('tiger:oainfo:add')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Oainfo oainfo) {
        return toAjax(oainfoService.insertOainfo(oainfo));
    }



    /**
     * 删除OA消息待办已办
     */
//    @ApiOperation(value = "删除OA消息待办已办")
//    //@PreAuthorize("@ss.hasPermi('tiger:oainfo:remove')")
////    @Log(title = "OA消息待办已办", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids) {
//        return toAjax(oainfoService.deleteOainfoByIds(ids));
//    }


    /**
     * 获取OA流程token
     */
    @ApiOperation(value = "获取OA的token")
    @GetMapping("/getToken")
    public AjaxResult getToken(@ApiParam(value = "REST账号") String userName, @ApiParam(value = "REST密码") String passWord,
                               @ApiParam(value = "OA账号") String loginName) {
        return AjaxResult.success(oainfoService.getToken(userName, passWord,loginName));
    }

    /**
     * 合同发起提交审核
     */
    @ApiOperation(value = "合同发起提交审核")
    @PostMapping("/oaContractSponsor")
    public AjaxMapResult oaContractSponsor(@RequestBody ContractSponsor contractSponsor) throws IOException {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxMapResult.success(oainfoService.oaContractSponsor(contractSponsor,loginUser));
    }


    @ApiOperation(value = "OA文件上传")
    @PostMapping("/oafile")
    public JSONObject getOaFile(MultipartFile upload, HttpServletRequest requests) throws Exception {
        String token = requests.getParameter("token");
        String url = "http://www.ntgrzc.com/seeyon/rest/attachment?token="+token;
        File file = null;
        //httpclients构造post请求
        // CloseableHttpClient httpClient = HttpClients.createDefault();
        file = multipartFileToFile(upload);
        String path = file.getAbsolutePath();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("imagefile", upload.getOriginalFilename(),
                        okhttp3.RequestBody.create(MediaType.parse("image/*"),
                                new File(path)))
                .addFormDataPart("serialnum", "1")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", (okhttp3.RequestBody) body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        Response response = client.newCall(request).execute();

        return JSONObject.parseObject(response.body().string());
    }



    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @Autowired
    private AssetMapper assetMapper;

    @ApiOperation(value = "资产信息XML格式")
    @GetMapping("/writeToXML")
    public String writeToXML() {

        Asset asset = new Asset();
        List<Asset> assetList = assetMapper.selectAssetList(asset);
        StringBuffer strBuffer = new StringBuffer("<root>");
        Map<String, Object> userMap = new HashMap<String, Object>();
        String returnstr="";
        try {
            for (Asset record : assetList) {
                strBuffer.append("<item>");
                Map<String, Object> params = record.getParams();
                userMap = JSON.parseObject(JSON.toJSONString(record), new TypeReference<Map<String, String>>() {
                });
                for(Map.Entry<String, Object> entry : userMap.entrySet()){
                    if(entry.getValue() instanceof List) {
                        strBuffer.append("<"+entry.getKey()+">");
                        for(Asset re:(List<Asset>)entry.getValue()) {
                            Map<String, Object> cols= re.getParams();
                            for(Map.Entry<String, Object> entry2 : cols.entrySet()){
                                strBuffer.append("<"+entry2.getKey()+">"+entry2.getValue()==null?"":entry2.getValue().toString()+"</"+entry2.getKey()+">");
                            }
                        }
                        strBuffer.append("</"+entry.getKey()+">");
                    }else {
                        String str = "<"+entry.getKey()+">"+(entry.getValue()==null?"":entry.getValue().toString())+"</"+entry.getKey()+">";
                        strBuffer.append(str);
                    }

                }
                strBuffer.append("</item>");
                //root.appendChild(item);
            }

            strBuffer.append("</root>");
            returnstr = URLEncoder.encode(strBuffer.toString(), "gb2312").replaceAll("\\+", "%20");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println(strBuffer.toString());

        return returnstr;
    }


    /**
     * 获取OA流程信息
     */
    @PostMapping("/getFlowInfo")
    @ApiOperation(value = "获取OA流程信息")
    public AjaxResult getFlowInfo(@RequestBody FlowInfo flowInfo) throws UnsupportedEncodingException {
        String oaUrl = oainfoService.getOaUrl(flowInfo.getOaFile(), flowInfo.getLoginName());
        return AjaxResult.success(oaUrl);
    }

    /**
     * 单点登录OA
     */
    @PostMapping("/singleLogin")
    @ApiOperation(value = "单点登录--OA")
    public AjaxResult singleLogin(@RequestBody FlowInfo flowInfo) {
        String s = oainfoService.singleLogin(flowInfo.getFrom(), flowInfo.getLoginName());
        return AjaxResult.success(s);
    }

    /**
     * 租金减免OA审批
     */
    @ApiOperation(value = "租金减免提交审批")
    @PostMapping("/getCredit")
    public AjaxMapResult getCredit(@RequestBody ContractSponsorCredit contractSponsorCredit) throws IOException {
        return AjaxMapResult.success(oainfoService.oaContractSponsorCredit(contractSponsorCredit));
    }

    /**
     * 开票申请OA提交审批
     */
    @ApiOperation(value = "开票申请提交审批")
    @PostMapping("/getBill")
    public AjaxMapResult getBill(@RequestBody ContractBill contractBill) throws IOException {
        return AjaxMapResult.success(oainfoService.oaContractBill(contractBill));
    }


    /**
     * 押金变更提交审批
     */
    @ApiOperation(value = "押金变更提交审批")
    @PostMapping("/getDepositChange")
    public AjaxMapResult getDepositChange(@RequestBody ContractSponsor contractSponsor) throws IOException {
        return AjaxMapResult.success(oainfoService.oaDepositChange(contractSponsor));
    }

    /**
     * 押金收款提交审批
     */
    @ApiOperation(value = "押金收款提交审批")
    @PostMapping("/getDepositPayee")
    public AjaxMapResult getDepositPayee(@RequestBody ContractSponsor contractSponsor) throws IOException {
        return AjaxMapResult.success(oainfoService.oaDepositPayee(contractSponsor));
    }

    /**
     * 押金退款提交审批
     */
    @ApiOperation(value = "押金退款提交审批")
    @PostMapping("/getDepositRefund")
    public AjaxMapResult getDepositRefund(@RequestBody ContractSponsor contractSponsor) throws IOException {
        return AjaxMapResult.success(oainfoService.oaDepositRefund(contractSponsor));
    }

    /**
     * 租金进账提交审批
     */
    @ApiOperation(value = "租金进账提交审批")
    @PostMapping("/oaRecord")
    public AjaxMapResult oaRecord(@RequestBody ContractBill contractBill) throws Exception {
        return AjaxMapResult.success(oainfoService.oaRecord(contractBill));
    }

    /**
     * 租金到账提交审批
     */
    @ApiOperation(value = "租金到账提交审批")
    @PostMapping("/oaArrival")
    public AjaxMapResult oaArrival(@RequestBody ContractBill contractBill) throws Exception {
        return AjaxMapResult.success(oainfoService.oaArrival(contractBill));
    }
    /**
     * 维修项目提交审批
     */
    @ApiOperation(value = "维修项目提交审批")
    @PostMapping("/oaMaintenanceApply")
    public AjaxMapResult oaMaintenanceApply(@RequestBody MaintenanceApply maintenanceApply) throws Exception {
        return AjaxMapResult.success(oainfoService.oaMaintenanceApply(maintenanceApply));
    }

    /**
     * 建设项目提交审批
     */
    @ApiOperation(value = "建设项目提交审批")
    @PostMapping("/oaConstructionApply")
    public AjaxMapResult oaConstructionApply(@RequestBody ConstructionApply constructionApply) throws Exception {
        return AjaxMapResult.success(oainfoService.oaConstructionApply(constructionApply));
    }
    /**
     * 项目验收提交审批
     */
    @ApiOperation(value = "项目验收提交审批")
    @PostMapping("/oaProjectAcceptance")
    public AjaxMapResult oaProjectAcceptance(@RequestBody ProjectAcceptance projectAcceptance) throws Exception {
        return AjaxMapResult.success(oainfoService.oaProjectAcceptance(projectAcceptance));
    }


    /**
     * 获取OA待办信息
     */
    @ApiOperation(value = "获取OA待办信息")
    @GetMapping("/backlog")
    public AjaxResult backlog(@ApiParam(value = "页数") Integer page, @ApiParam(value = "每页数量") Integer pageSize,
                               @ApiParam(value = "OA的token") String token,@ApiParam(value = "OA登录名") String loginName) {
        return AjaxResult.success(oainfoService.backlog(page,pageSize,loginName,token));
    }

    /**
     * 获取OA已办信息
     */
    @ApiOperation(value = "获取OA已办信息")
    @GetMapping("/replied")
    public AjaxResult replied(@ApiParam(value = "页数") Integer page, @ApiParam(value = "每页数量") Integer pageSize,
                              @ApiParam(value = "OA的token") String token,@ApiParam(value = "OA登录名") String loginName) {
        return AjaxResult.success(oainfoService.replied(page,pageSize,loginName,token));
    }

}
